// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: daniel

#include "coin2/exchange/bithumb/api_util/order_manager.h"

#include "coin2/base/time.h"
#include "coin2/exchange/bithumb/symbology/product.h"

namespace coin2::exchange::bithumb::api_util {

bool RateLimitPreventMode() {
  static bool mode = []() -> auto {
    char const* mode = getenv("RATE_LIMIT_SAVE_MODE");
    if (mode != nullptr && std::string(mode) == "1") {
      LOG(INFO) << "Set RATE_LIMIT_SAVE_MODE = true";
      return true;
    } else {
      LOG(INFO) << "Set RATE_LIMIT_SAVE_MODE = false";
      return false;
    }
  }
  ();
  return mode;
}

auto OrderManager::GetOpenOrdersCopy() const -> OrderMap { return open_orders_map_; }

void OrderManager::ProcessOpenOrder(const std::string& order_id, const std::string& currency) {
  if (Find(order_id)) {
    return;
  }
  using BithumbProduct = coin2::exchange::bithumb::symbology::BithumbProduct;
  auto product = BithumbProduct::FromStr(currency, impl::GetCurrentTimestamp());
  const auto& order_currency = product.base().native_currency();
  const auto& payment_currency = product.quote().native_currency();
  auto order = std::make_shared<OrderCache>(order_id, order_currency, payment_currency);
  AddOpenOrder(order);
}

void OrderManager::ProcessClosedOrder(const std::string& order_id) {
  if (!Find(order_id)) {
    return;
  }
  DelOpenOrder(order_id);
}

bool OrderManager::Find(const std::string& order_id) const {
  return open_orders_map_.count(order_id) > 0;
}

void OrderManager::AddOpenOrder(const OrderCachePtr& order) {
  if (!order || order->IsEmpty()) {
    return;
  }
  if (open_orders_map_.count(order->order_id) > 0) {
    return;
  }
  open_orders_map_.emplace(order->order_id, order);
}

void OrderManager::DelOpenOrder(const std::string& order_id) {
  if (order_id.empty() || open_orders_map_.count(order_id) == 0) {
    return;
  }
  open_orders_map_.erase(order_id);
}

}  // namespace coin2::exchange::bithumb::api_util
